<template>
  <div class="app-container">
    <!-- 查询 -->
    <div class="filter-container">
      <el-row :gutter="0">
        <el-form :inline="true" class="search-form">
          <el-form-item label="实例ID">
            <el-input v-model="query.instance_id" class="filter-item" placeholder="请输入实例ID" clearable />
          </el-form-item>
          <el-form-item label="开发者">
            <el-input v-model="query.nickname" class="filter-item" placeholder="请输入开发者" clearable />
          </el-form-item>
          <el-form-item>
            <el-button class="" type="primary" icon="el-icon-search" @click="search">查询</el-button>
            <el-button class="" type="success" icon="el-icon-refresh-right" plain @click="refresh()">刷新</el-button>
            <el-button v-if="$isRouteAllowed('adminapi/Vm/add')" class="" type="primary" icon="el-icon-plus" plain @click="add()">添加</el-button>
          </el-form-item>

          <el-form-item style="float: right" />
        </el-form>
      </el-row>
    </div>
    <!-- 列表 -->
    <el-table ref="tableRef" v-loading="loading" :data="datas" :max-height="height" border style="width: 100%">
      <!--<el-table-column prop="id" label="ID" min-width="60" align="center" />-->
      <el-table-column prop="name" label="名称" min-width="120" align="center" />
      <!--<el-table-column prop="instance_id" label="实例ID" min-width="120" align="center" />-->
      <!--<el-table-column prop="type_name" label="类型" min-width="60" align="center" />-->
      <el-table-column prop="status" label="状态" min-width="60" align="center">
        <template slot-scope="{ row }">
          <el-tag :type="row.status === 'running' ? 'success' : row.status === 'stopped' ? 'danger' : 'info'">{{ row.status }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="ip" label="IPv4" min-width="160" align="center" />
      <!--<el-table-column prop="nickname" label="授权用户" min-width="60" align="center" />-->
      <el-table-column label="操作" min-width="300" align="center" fixed="right">
        <template slot-scope="{ row }">
          <el-button v-if="row.status === 'stopped' && $isRouteAllowed('adminapi/Vm/start')" type="success" icon="el-icon-open" size="mini" @click="start(row)">开机</el-button>
          <el-button v-if="row.status === 'running' && $isRouteAllowed('adminapi/Vm/shoutDown')" type="danger" icon="el-icon-switch-button" size="mini" @click="shoutDown(row)">停机不计费</el-button>
          <el-button v-if="row.status === 'running' && $isRouteAllowed('adminapi/Vm/restart')" type="warning" icon="el-icon-refresh" size="mini" @click="restart(row)">强制重启</el-button>
          <el-button v-if="$isRouteAllowed('adminapi/Vm/delete')" type="info" icon="el-icon-delete" size="mini" @click="del(row)">删除</el-button>
          <el-button v-if="$isRouteAllowed('adminapi/Vm/edit')" type="primary" icon="el-icon-edit" size="mini" @click="edit(row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 添加、修改 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" top="10vh" :close-on-click-modal="false" :before-close="cancel">
      <el-form ref="formRef" :rules="rules" :model="model" label-width="100px" class="" :style="{height:height-120+'px'}">
        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="model.type" @change="regionOptions">
            <el-radio :label="1">阿里云</el-radio>
            <el-radio :label="2">腾讯云</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="实例ID" prop="instance_id">
          <el-input v-model="model.instance_id" maxlength="120" placeholder="" show-word-limit />
        </el-form-item>
        <el-form-item label="地域" prop="region_id">
          <el-select v-model="model.region_id" class="" placeholder="地域" filterable clearable>
            <el-option
              v-for="option in selectRegionOptions"
              :key="option.Region"
              :value="option.Region"
              :label="option.RegionName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="授权用户" prop="user_id">
          <el-select v-model="model.user_id" class="" placeholder="授权用户" multiple clearable>
            <el-option
              v-for="option in selectUsersOptions"
              :key="option.id"
              :value="option.id"
              :label="option.nickname"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button :loading="btnLoading" type="primary" @click="submit">提交</el-button>
      </div>
    </el-dialog>
    <!-- 分页 -->
    <pagination v-show="total > 0" :total="total" :page.sync="query.page" :limit.sync="query.limit" @pagination="list" />
  </div>
</template>

<script>
import screenHeight from '@/utils/screen-height'
import Pagination from '@/components/Pagination'
import { list, save, del, start, restart, shoutDown, regionList, getStatus } from '@/api/admin/vm'
import { options } from '@/api/admin/admin'

export default {
  name: 'AdminMember',
  components: { Pagination },
  data() {
    return {
      height: 680,
      loading: false,
      datas: [],
      total: 0,
      query: {
        page: 1,
        limit: 20,
        instance_id: '',
        nickname: ''
      },
      dialogVisible: false,
      dialogTitle: '',
      btnLoading: false,
      model: {
        id: '',
        region_id: '',
        user_id: [],
        instance_id: '',
        type: ''
      },
      rules: {},
      selectUsersOptions: [],
      refreshInterval: null, // 添加定时器变量
      selectRegionOptions: [],
      intervalStatus: false
    }
  },
  created() {
    this.height = screenHeight()
    this.list()
    this.startRefreshInterval() // 启动定时器
  },
  beforeDestroy() {
    this.stopRefreshInterval() // 清除定时器
  },
  methods: {
    permission(route) {
      console.log(this.$store.getters.roleRoutes)
      return this.$store.getters.roleRoutes.includes(route)
    },
    usersOptions() {
      options(this.query).then(res => {
        this.selectUsersOptions = res.data
        console.log(this.selectUsersOptions)
      }).catch(() => {
        this.loading = false
      })
    },
    regionOptions() {
      regionList({ type: this.model.type }).then(res => {
        this.selectRegionOptions = res.data
        console.log(this.selectRegionOptions)
      }).catch(() => {
        this.loading = false
      })
    },
    // 列表
    list() {
      this.loading = true
      list(this.query).then(res => {
        this.datas = res.data.data
        this.total = res.data.total
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    edit(row) {
      this.dialogVisible = true
      this.dialogTitle = '编辑：' + row.name
      // this.rowData.single_file = {
      //   url: row.head_image,
      //   path: row.head_image
      // }
      // this.rowData 循坏给他赋值
      // this.rowData = {}
      for (const key in row) {
        // eslint-disable-next-line no-prototype-builtins
        if (this.model.hasOwnProperty(key)) {
          this.model[key] = row[key]
        }
      }
      this.usersOptions()
    },
    // 删除
    del(row) {
      this.$confirm(
        '确定要删除ID： <span style="color:red">' + row.name + ' </span> 这条数据吗？',
        'ID：' + row.id,
        { type: 'warning', dangerouslyUseHTMLString: true }
      ).then(() => {
        this.loading = true
        del({
          id: row.id
        }).then(res => {
          this.list()
          this.$message.success(res.msg)
        }).catch(() => {
          this.loading = false
        })
      }).catch(() => {
      })
    },
    // 开机
    start(row) {
      this.$confirm(
        '确定要开机 <span style="color:red">' + row.name + ' </span> 这台机器吗？',
        'ID：' + row.instance_id,
        { type: 'warning', dangerouslyUseHTMLString: true }
      ).then(() => {
        this.loading = true
        start({
          instance_id: row.instance_id,
          region_id: row.region_id,
          type: row.type
        }).then(res => {
          this.refresh()
          this.$message.success(res.msg)
        }).catch((e) => {
          console.log(e)
          this.updateStatus([row.id])
          this.loading = false
        })
      }).catch(() => {
      })
    },
    // 强制重启
    restart(row) {
      this.$confirm(
        '确定要强制重启 <span style="color:red">' + row.name + ' </span> 这台机器吗？',
        'ID：' + row.instance_id,
        { type: 'warning', dangerouslyUseHTMLString: true }
      ).then(() => {
        this.loading = true
        restart({
          instance_id: row.instance_id,
          region_id: row.region_id,
          type: row.type
        }).then(res => {
          this.refresh()
          this.$message.success(res.msg)
        }).catch(() => {
          this.updateStatus([row.id])
          this.loading = false
        })
      }).catch(() => {
      })
    },
    // 停机不计费
    shoutDown(row) {
      this.$confirm(
        '确定要停机不计费 <span style="color:red">' + row.name + ' </span> 这台机器吗？',
        'ID：' + row.instance_id,
        { type: 'warning', dangerouslyUseHTMLString: true }
      ).then(() => {
        this.loading = true
        shoutDown({
          instance_id: row.instance_id,
          region_id: row.region_id,
          type: row.type
        }).then(res => {
          this.refresh()
          this.$message.success(res.msg)
        }).catch(() => {
          this.updateStatus([row.id])
          this.loading = false
        })
      }).catch(() => {
      })
    },
    // 查询
    search() {
      this.query.page = 1
      this.list()
    },
    // 刷新
    refresh() {
      this.query = this.$options.data().query
      this.list()
    },
    // 添加
    add() {
      this.dialogVisible = true
      this.dialogTitle = '新增'
      this.reset()
      this.usersOptions()
    },
    // 取消
    cancel() {
      this.dialogVisible = false
      this.reset()
    },
    // 重置
    reset(row) {
      if (row) {
        this.model = row
      } else {
        this.model = this.$options.data().model
      }
      if (this.$refs['formRef'] !== undefined) {
        this.$refs['formRef'].resetFields()
      }
    },
    // 提交
    async submit() {
      this.$refs['formRef'].validate(valid => {
        if (valid) {
          this.btnLoading = true
          save(this.model).then(res => {
            this.btnLoading = false
            this.list()
            this.dialogVisible = false
            this.$message.success(res.msg)
          }).catch(() => {
            this.btnLoading = false
          })
        }
      })
    },
    // 启动定时器
    startRefreshInterval() {
      this.refreshInterval = setInterval(() => {
        this.updateStatus()
        // 打印时间
        console.log('定时器已启动:' + new Date().toLocaleTimeString())
      }, 3000) // 每3秒刷新一次
    },
    // 停止定时器
    stopRefreshInterval() {
      console.log('定时器停止:' + new Date().toLocaleTimeString())
      if (this.refreshInterval) {
        clearInterval(this.refreshInterval)
        this.refreshInterval = null
      }
    },
    // 更新状态
    // 只更新 datas 中 status == stoping starting 的数据
    updateStatus(id) {
      // 如果id 为空，则获取当前页的数据id
      if (!id) {
        console.log(this.intervalStatus)
        if (this.intervalStatus) {
          console.log('上一次请求未完成，跳过本次循环')
          return
        }
        this.intervalStatus = true
        // 获取当前页的数据id
        id = this.datas.map(item => item.id)
      }
      if (id.length !== 0) {
        getStatus({ id }).then(res => {
          const udata = res.data.data
          // 将res.data.data 中的数据更新到 this.datas 中
          for (let i = 0; i < udata.length; i++) {
            for (let j = 0; j < this.datas.length; j++) {
              if (this.datas[j].id === udata[i].id) {
                this.datas[j].status = udata[i].status
                this.datas[j].user_id = udata[i].user_id
              }
              // console.log(udata[i].instance_id + ':' + udata[i].status)
            }
          }
          this.intervalStatus = false
          // console.log(udata[0].status)
          // console.log(this.datas[0].status)
        }).catch((e) => {
          // 处理错误
          console.error('更新状态失败')
          console.error(e)
          this.intervalStatus = false
        }).finally((e) => {
          console.log('finally')
          this.intervalStatus = false
        })
      } else {
        this.intervalStatus = false
      }
    }
  }
}
</script>
